package com.shujia.custom.udtf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;

public class MyUDTFDemo2 extends GenericUDTF {
    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
        //创建两个集合，这两个集合是一一对应的关系
        //一个是列名的集合
        ArrayList<String> colNameList = new ArrayList<>();
        colNameList.add("id");
        colNameList.add("time");
        colNameList.add("value");
        //另一个是列数据类型的集合
        ArrayList<ObjectInspector> colTypeList = new ArrayList<>();
        colTypeList.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        colTypeList.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        colTypeList.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        //将列名集合和列数据类型集合对应返回
        return ObjectInspectorFactory.getStandardStructObjectInspector(colNameList, colTypeList);
    }

    @Override
    public void process(Object[] args) throws HiveException {
        String[] infos = new String[3];
        //a,1,2,3,4,5,6,7,8,9,10,11,12
        //输出：
        // a  0时  1
        String id = args[0].toString();
        infos[0] = id;
        int t = 0;
        for (int i = 1; i < args.length; i++) {
            infos[1] = t + "时";
            infos[2] = args[i].toString();
            forward(infos);
            t += 2;
        }
    }

    @Override
    public void close() throws HiveException {

    }
}
